/**
 * Title TokenUtils
 * Package com.ruoyi.common.utils
 * Copyright 2024 www.hundsun.com All Rights Reserved.
 *
 * @author gd
 * @date 2024/9/9 2:02 AM
 * @version V5.1.2
 */
package com.ruoyi.common.utils;

import com.ruoyi.common.utils.uuid.UUID;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;

import java.security.SecureRandom;
import java.util.Base64;
import java.util.Date;

/**
 * token管理
 * ClassName TokenUtils
 * @author gd
 * @date 2024/9/9 2:02 AM
 */
public class TokenUtils {

    private static final String SECRET_KEY = "your-secret-key";
    /**
     * 1 day
     */
    private static final long EXPIRATION = 86400000;
    /**
     * 可以根据需要调整长度
     */
    private static final int KEY_LENGTH = 64;


    public static String generateToken(String userId) {
        return Jwts.builder()
                .setSubject(userId)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .signWith(SignatureAlgorithm.HS512, SECRET_KEY.getBytes())
                .compact();
    }

    public static boolean validateToken(String token,String userId) throws SignatureException {
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET_KEY.getBytes())
                .parseClaimsJws(token)
                .getBody();
        String oldUserId = claims.getSubject();
        return userId.equals(oldUserId);
    }

    public static String getToken(){
        return UUID.randomUUID().toString();
    }


    public static String generateRandomSecretKey() {
        SecureRandom random = new SecureRandom();
        byte[] key = new byte[KEY_LENGTH];
        random.nextBytes(key);
        return Base64.getEncoder().encodeToString(key);
    }

    public static void main(String[] args) {
        String secretKey = TokenUtils.generateRandomSecretKey();
        System.out.println("Generated Secret Key: " + secretKey);
    }
}